import { ipcMain, dialog, app, BrowserWindow } from 'electron'
import {
  IPCHandler,
  IPCChannels,
  StandardResponse,
  ResponseCode,
  createStandardResponse,
  createStandardErrorResponse,
  createSuccessResponse,
  createErrorResponse,
  IPCError
} from './types'
import { log } from '../services/logger'
// import { getDataSource } from '../database/connection'
// import { Project } from '../database/entities/Project'
import * as projectService from '../services/projectService'
import os from 'os'
import path from 'path'

/**
 * 类型安全的IPC处理器注册函数
 */
function registerHandler<T extends keyof IPCChannels>(
  channel: T,
  handler: IPCHandler<T>
): void {
  ipcMain.handle(channel, async (event, args) => {
    const startTime = performance.now()

    try {
      log.ipc(channel, 'receive', { args })

      const result = await handler(event, args)
      const endTime = performance.now()

      log.performance(`IPC处理: ${channel}`, endTime - startTime)
      log.ipc(channel, 'send', { result })

      // 返回标准响应格式
      return createStandardResponse(result, '操作成功', ResponseCode.SUCCESS)
    } catch (error) {
      const endTime = performance.now()
      const errorMessage = error instanceof Error ? error.message : String(error)
      const errorStack = error instanceof Error ? error.stack : undefined

      log.error(`IPC处理失败: ${channel}`, {
        error: errorMessage,
        stack: errorStack,
        args,
        duration: endTime - startTime
      })

      // 根据错误类型返回不同的状态码
      let code = ResponseCode.INTERNAL_ERROR
      if (error instanceof IPCError) {
        switch (error.code) {
          case 'PROJECT_NOT_FOUND':
          case 'NOT_FOUND':
            code = ResponseCode.NOT_FOUND
            break
          case 'VALIDATION_ERROR':
            code = ResponseCode.VALIDATION_ERROR
            break
          case 'BAD_REQUEST':
            code = ResponseCode.BAD_REQUEST
            break
          default:
            code = ResponseCode.INTERNAL_ERROR
        }
      }

      return createStandardErrorResponse(errorMessage, code)
    }
  })
}

/**
 * 项目相关处理器
 */
const projectHandlers = {
  'project:create': async (_event, args) => {
    // 验证输入参数
    if (!args.name || args.name.trim().length === 0) {
      throw new IPCError('项目名称不能为空', 'VALIDATION_ERROR', { field: 'name' })
    }

    if (args.name.length > 100) {
      throw new IPCError('项目名称不能超过100个字符', 'VALIDATION_ERROR', { field: 'name' })
    }

    const projectData = {
      name: args.name.trim(),
      description: (args as any).description || '',
      resolution: args.resolution || { width: 1280, height: 720 },
      frameRate: args.frameRate || 30
    }

    try {
      const savedProject = await projectService.createProject(projectData)
      log.database('项目创建', 'projects', { projectId: savedProject.id })
      return savedProject
    } catch (error) {
      log.error('项目创建失败', { error: error instanceof Error ? error.message : String(error), projectData })
      throw new IPCError('项目创建失败', 'DATABASE_ERROR', { originalError: error })
    }
  },

  'project:open': async (_event, args) => {
    let project = null

    if (args.id) {
      project = await projectService.getProjectById(args.id)
    } else if (args.path) {
      // TODO: 实现按路径查找项目
      throw new IPCError('按路径打开项目功能尚未实现', 'NOT_IMPLEMENTED', args)
    }

    if (!project) {
      throw new IPCError('项目不存在', 'PROJECT_NOT_FOUND', args)
    }

    // 更新最后打开时间
    await projectService.updateProjectLastOpened(project.id)

    log.database('项目打开', 'projects', { projectId: project.id })
    return project
  },

  'project:save': async (_event, args) => {
    // 验证项目ID
    if (!args.id) {
      throw new IPCError('项目ID不能为空', 'VALIDATION_ERROR', { field: 'id' })
    }

    const project = await projectService.getProjectById(args.id)
    if (!project) {
      throw new IPCError('项目不存在', 'PROJECT_NOT_FOUND', { id: args.id })
    }

    try {
      if (args.data) {
        // 验证更新数据
        if (args.data.name !== undefined) {
          if (!args.data.name || args.data.name.trim().length === 0) {
            throw new IPCError('项目名称不能为空', 'VALIDATION_ERROR', { field: 'name' })
          }
          if (args.data.name.length > 100) {
            throw new IPCError('项目名称不能超过100个字符', 'VALIDATION_ERROR', { field: 'name' })
          }
          args.data.name = args.data.name.trim()
        }

        await projectService.updateProject(args.id, args.data)
        log.database('项目保存', 'projects', { projectId: args.id, updatedFields: Object.keys(args.data) })
      } else {
        log.database('项目保存', 'projects', { projectId: args.id, note: '无数据更新' })
      }

      return true
    } catch (error) {
      log.error('项目保存失败', { error: error instanceof Error ? error.message : String(error), projectId: args.id })
      if (error instanceof IPCError) {
        throw error
      }
      throw new IPCError('项目保存失败', 'DATABASE_ERROR', { originalError: error })
    }
  },

  'project:delete': async (_event, args) => {
    const success = await projectService.deleteProject(args.id)

    if (success) {
      log.database('项目删除', 'projects', { projectId: args.id })
    }

    return success
  },

  'project:list': async (_event, _args) => {
    const projects = await projectService.getAllProjects()

    log.database('项目列表查询', 'projects', { count: projects.length })
    return projects
  },

  'project:getAll': async (_event, _args) => {
    const projects = await projectService.getAllProjects()

    log.database('获取所有项目', 'projects', { count: projects.length })
    return projects
  },

  'project:export': async (_event, args) => {
    // 验证输入参数
    if (!args.id) {
      throw new IPCError('项目ID不能为空', 'VALIDATION_ERROR', { field: 'id' })
    }

    if (!args.format || !['mp4', 'gif', 'webm'].includes(args.format)) {
      throw new IPCError('不支持的导出格式', 'VALIDATION_ERROR', { field: 'format', supportedFormats: ['mp4', 'gif', 'webm'] })
    }

    // 检查项目是否存在
    const project = await projectService.getProjectById(args.id)
    if (!project) {
      throw new IPCError('项目不存在', 'PROJECT_NOT_FOUND', { id: args.id })
    }

    try {
      // 生成导出文件路径
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
      const fileName = `${project.name}_${timestamp}.${args.format}`
      const exportPath = path.join(app.getPath('downloads'), fileName)

      // TODO: 这里应该实现实际的导出逻辑
      // 目前返回模拟结果
      log.info('项目导出请求', {
        projectId: args.id,
        projectName: project.name,
        format: args.format,
        options: args.options,
        exportPath
      })

      // 模拟导出过程
      await new Promise(resolve => setTimeout(resolve, 1000))

      log.database('项目导出', 'projects', {
        projectId: args.id,
        format: args.format,
        exportPath
      })

      return { path: exportPath }
    } catch (error) {
      log.error('项目导出失败', {
        error: error instanceof Error ? error.message : String(error),
        projectId: args.id,
        format: args.format
      })
      if (error instanceof IPCError) {
        throw error
      }
      throw new IPCError('项目导出失败', 'FILE_ERROR', { originalError: error })
    }
  }
} satisfies Record<string, IPCHandler<any>>

/**
 * 系统相关处理器
 */
const systemHandlers = {
  'system:info': async (_event, _args) => {
    const memInfo = process.memoryUsage()
    const cpus = os.cpus()
    
    return {
      platform: process.platform,
      arch: process.arch,
      version: app.getVersion(),
      memory: {
        total: os.totalmem(),
        free: os.freemem(),
        used: memInfo.heapUsed
      },
      cpu: {
        model: cpus[0]?.model || 'Unknown',
        cores: cpus.length,
        usage: 0 // 实际使用中可以计算CPU使用率
      }
    }
  },

  'system:openDialog': async (_event, args) => {
    const result = await dialog.showOpenDialog({
      properties: args.type === 'directory' ? ['openDirectory'] : ['openFile'],
      filters: args.filters
    })
    
    return {
      paths: result.filePaths,
      canceled: result.canceled
    }
  },

  'system:showSaveDialog': async (_event, args) => {
    const result = await dialog.showSaveDialog({
      defaultPath: args.defaultPath,
      filters: args.filters
    })
    
    return {
      path: result.filePath,
      canceled: result.canceled
    }
  }
} satisfies Record<string, IPCHandler<any>>

/**
 * 应用相关处理器
 */
const appHandlers = {
  'app:version': async (_event, _args) => {
    return app.getVersion()
  },

  'app:quit': async (_event, _args) => {
    app.quit()
  },

  'app:minimize': async (event, _args) => {
    const window = BrowserWindow.fromWebContents(event.sender)
    window?.minimize()
  },

  'app:maximize': async (event, _args) => {
    const window = BrowserWindow.fromWebContents(event.sender)
    if (window?.isMaximized()) {
      window.unmaximize()
    } else {
      window?.maximize()
    }
  },

  'app:close': async (event, _args) => {
    const window = BrowserWindow.fromWebContents(event.sender)
    window?.close()
  }
} satisfies Record<string, IPCHandler<any>>

/**
 * 注册所有IPC处理器
 */
export function registerAllHandlers(): void {
  // 注册项目处理器
  Object.entries(projectHandlers).forEach(([channel, handler]) => {
    registerHandler(channel as keyof IPCChannels, handler)
  })

  // 注册系统处理器
  Object.entries(systemHandlers).forEach(([channel, handler]) => {
    registerHandler(channel as keyof IPCChannels, handler)
  })

  // 注册应用处理器
  Object.entries(appHandlers).forEach(([channel, handler]) => {
    registerHandler(channel as keyof IPCChannels, handler)
  })

  log.info('所有IPC处理器已注册', {
    projectHandlers: Object.keys(projectHandlers).length,
    systemHandlers: Object.keys(systemHandlers).length,
    appHandlers: Object.keys(appHandlers).length
  })
}
